<template>
  <div class="home">
    <el-container>
      <el-header>
        <h1 class="title">欢迎来到在线聊天室</h1>
      </el-header>
      <el-container>
        <el-aside class="side_bar">
          <div class="userlist_panel">
            <div class="user_header">在线用户：{{ onlineCounts }}人</div>
            <div id="u-list" class="u-list">
              <ul v-for="(item, index) in onLineUser" :key="index">
                <li>
                  <a href="javascript:void(0);" @click="selectUser($event)">{{
                    item
                  }}</a>
                </li>
              </ul>
            </div>
          </div>
        </el-aside>
        <el-container>
          <el-main>
            <div class="chat_panel chat-content">
              <div 
                id="message"
                v-html="message"
                style="text-align: left; width: 100%"
              ></div>
            </div>
          </el-main>
        </el-container>
      </el-container>
    </el-container>
    <hr />
    <br />
    <el-row class="el-row" :gutter="20">
      <el-col :span="5"
        ><el-form>
          <el-form-item label="用户名:" label-width="60px">
            <el-input
              type="text"
              size="mini"
              id="username"
              v-model="username"
              :disabled="isUsername"
              placeholder="请输入昵称"
            ></el-input>
          </el-form-item>
          <el-form-item class="item_btn" label-width="80px">
            <el-button type="primary" size="mini" :disabled="isOpenBtn" @click="Open()"
              >连接服务</el-button
            >
            <el-button
              type="danger" size="mini"
              :disabled="isCloseBtn"
              @click="closeWebSocket()"
              >关闭服务</el-button
            >
          </el-form-item>
        </el-form></el-col
      >

      <el-col :span="3">
        <el-select size="mini" v-model="selected" placeholder="请选择">
          <el-option
            v-for="(item, index) in onLineUser"
            :key="index"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-col>

      <el-col :span="6">
        <div class="chat-bar">
          <i
            @click="show_emot()"
            class="fa fa-smile-o"
          ></i>
          <div v-if="show" class="chat-emotion">
            <ul class="emot-list clearfix">
              <li v-for="(item, index) in emot_list" :key="index">
                <img
                  @click="select_emot(item.id)"
                  v-bind:alt="item.id"
                  v-bind:src="item.src"
                />
              </li>
            </ul>
          </div>
          <i class="el-icon-star-off mg-l20"></i>
        </div>
        <el-input
          type="textarea"
          
          :rows="8"
          :cols="50"
          :disabled="isTextArea"
          v-model="sendMessage"
          @keyup.enter.native="Send()"
          maxlength="120"
          show-word-limit
        ></el-input>
      </el-col>
      <el-col :span="3">
        <el-button
          type="primary"
          id="sendbtn"
          size="mini"
          :disabled="isSendBtn"
          @click="Send()"
        >
          发送消息(Enter)
        </el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// @ is an alias to /src

export default {
  name: "HomeView",
  components: {},
  data() {
    return {
      username: "",
      onLineUser: ["--所有人--"],
      onlineCounts: 0,
      webSocket: null,
      heartCheck: null,
      isUsername: false,
      isOpenBtn: false,
      isCloseBtn: true,
      isSendBtn: true,
      isTextArea: true,
      sendMessage: "",
      selected: "--所有人--",
      message: "",
      show: false,
      emot_num: 75,
      emot_list: [],
      imgsrc: "../assets/emot/$1.gif",
    };
  },
  created() {
    //window.addEventListener('keydown', this.handkeyCode, true)//开启监听键盘按下事件
  },
  mounted() {
    // 根据不同路由跳转不同页面
    if (this._isMobile()) {
      this.$router.replace('/m')
    }
    this.init_emot();
  },
  methods: {
    // 判断是否是手机端，如果是，返回true
    _isMobile () {
      let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
      return flag
    },
    init() {
      const _this = this;
      //console.log(this.username);
      //wss://www.archeage.top/chatroomserver/websocket/
      _this.webSocket = new WebSocket(
        "ws://localhost:8080/websocket/" + this.username
      );

      //连通之后的回调事件
      _this.webSocket.onopen = function () {
        _this.setMessageInnerHTML(
          "<b>系统通知：您已成功进入聊天室，请自觉维护聊天室的正常秩序！</b>"
        );
        //连接按钮禁用，其他按钮启用
        _this.isUsername = true;
        _this.isOpenBtn = true;
        _this.isCloseBtn = false;
        _this.isSendBtn = false;
        _this.isTextArea = false;
        //设置心跳机制
        _this.heartCheck = setInterval(()=> {
          _this.webSocket.send("HeartBeat");
        }, 50000); // 发送心跳消息的时间间隔，单位毫秒
      };

      //接收后台服务端的消息
      _this.webSocket.onmessage = function (evt) {
        //clearInterval(_this.heartCheck);
        // _this.heartCheck = setInterval(function () {
        //   _this.webSocket.send("HeartBeat");
        // }, 5000);
        let received_msg = evt.data;
        console.log("数据已接收:" + received_msg);
        let obj = JSON.parse(received_msg);
        console.log("可以解析成json:" + obj.messageType);
        //1代表上线 2代表下线 3代表在线名单 4代表普通消息
        if (obj.messageType == 1) {
          //有新用户上线
          //把名称放入到selection当中供选择
          let onlineName = obj.username;
          let option = onlineName;
          _this.onLineUser.push(option);
          _this.setMessageInnerHTML("系统通知：" + onlineName + "上线了");
          _this.onlineCounts++;
        } else if (obj.messageType == 2) {
          //有用户下线，将用户移除
          _this.onLineUser = ["--所有人--"];
          let onlineName = obj.onlineUsers;
          let offlineName = obj.username;
          for (let i = 0; i < onlineName.length; i++) {
            if (!(onlineName[i] == _this.username)) {
              _this.onLineUser.push(onlineName[i]);
            }
          }

          _this.onlineCounts--;
          _this.setMessageInnerHTML("系统通知：" + offlineName + "下线了");
        } else if (obj.messageType == 3) {
          //用户上线接收在线数据
          _this.onLineUser = ["--所有人--"];
          let onlineName = obj.onlineUsers;
          for (let i = 0; i < onlineName.length; i++) {
            if (!(onlineName[i] == _this.username)) {
              //如果在线用户不等于自己，将用户加入列表中
              _this.onLineUser.push(onlineName[i]);
            }
          }
          //更新在线人数
          _this.onlineCounts = onlineName.length;

          console.log("获取了在线的名单" + onlineName.toString());
        } else {
          if (obj.tousername == _this.username) {
            _this.setMessageInnerHTML(
              obj.fromusername + "对你说：" + _this.replace_em(obj.textMessage)
            );
          } else {
            _this.setMessageInnerHTML(
              obj.fromusername +
                "对" +
                obj.tousername +
                "说：" +
                _this.replace_em(obj.textMessage)
            );
          }
          _this.scrollToBottom();
        }
      };

      //连接关闭的回调事件
      _this.webSocket.onclose = function () {
        //console.log("连接已关闭...");
        _this.setMessageInnerHTML("退出聊天室，连接已经关闭....");
        //清空列表
        _this.onLineUser = [];
        _this.onLineUser.push("--所有人--");
        clearInterval(_this.heartCheck); //清除定时器
      };
    },
    // 点击选择用户
    selectUser(e) {
      //console.log(e.target.innerHTML);
      this.selected = e.target.innerHTML;
    },
    Open() {
      if (this.username.trim() == "") {
        this.$message.error("昵称不能为空");
        this.username = "";
        return;
      } else {
        this.init();
      }
    },
    closeWebSocket() {
      //直接关闭websocket的连接
      this.webSocket.close();
      clearInterval(this.heartCheck); //清除定时器
      //连接按钮禁用，其他按钮启用
      this.isUsername = false;
      this.isOpenBtn = false;
      this.isCloseBtn = true;
      this.isSendBtn = true;
      this.isTextArea = true;
    },
    setMessageInnerHTML(innerHTML) {
      this.message += innerHTML + "<br/>";
    },
    Send() {
      const _this = this;
      // clearInterval(_this.heartCheck);
      // _this.heartCheck = setInterval(function () {
      //   _this.webSocket.send("HeartBeat");
      // }, 5000);

      if (_this.sendMessage.trim() == "" || _this.sendMessage.trim() == null) {
        this.$message.error("输入内容不能为空！");
        return;
      }

      let selectText = this.selected;
      //console.log("发送方法");
      if (selectText == "--所有人--") {
        selectText = "All";
      } else {
        //console.log("私信中");
        _this.setMessageInnerHTML(
          "你" + "对" + selectText + "说：" + _this.replace_em(this.sendMessage)
        );
      }
      let message = {
        message: this.sendMessage.trim(),
        username: this.username,
        to: selectText,
      };
      _this.webSocket.send(JSON.stringify(message));
      _this.sendMessage = "";
      _this.scrollToBottom();
    },
    //表情包
    init_emot() {
      //初始化方法
      var _this = this;
      //默认生成表情列表
      for (let i = 1; i <= _this.emot_num; i++) {
        var emot = new Object();
        emot.id = i;
        emot.src = require("@/assets/emot/" + i + ".gif");
        _this.emot_list.push(emot);
      }
    },
    show_emot() {
      this.show = !this.show;
    },
    select_emot(e) {
      //根据点击表情id生成快捷文字
      var el = e;
      var em_text = "[em_" + el + "]";
      //关闭表情选择器并将内容赋值到input表签内
      this.show = false;
      //console.log("test:"+em_text)
      //console.log(this.replace_em(testdata))
      this.sendMessage += em_text;
    },
    //查看显示结果
    replace_em(str) {
      str = str.replace(/\</g, "&lt;");

      str = str.replace(/\>/g, "&gt;");

      str = str.replace(/\n/g, "<br/>");

      str = str.replace(
        /\[em_([0-9]*)\]/g,
        '<img src="emot/$1.gif" border="0" />'
      );

      return str;
    },
    //定位消息在最后一行
    scrollToBottom() {
      this.$nextTick(() => {
        var container = this.$el.querySelector(".chat-content");
        container.scrollTop = container.scrollHeight;
      });
    },
  },
};
</script>
<style scoped>
.title {
  font-size: 24px;
}

.el-row {
  margin: 0 !important;
}

.user_header {
  font-size: 14px;
  padding: 20px;
  width: 200px;
}

.u-list {
  font-size: 18px;
}

.u-list a{
  font-size: 14px;
}

.chat_panel {
  text-align: right;
  height: 500px;
  overflow-y: auto;
  font-size: 18px;
  color: #000;
}

.login_panel {
  margin: 0 20px;
}

.message_box {
  width: 500px;
  height: 200px;
}

.mg-r20 {
  margin-right: 20px;
}

.mg-l20 {
  margin-left: 20px;
}

.el-header,
.el-footer {
  background-color: #409eff;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: rgb(217, 236, 255);
  color: #333;
  text-align: center;
}

.side_bar{
  max-width: 400px;
}

.el-main {
  background-color: rgb(236, 245, 255);
  color: #333;
  text-align: center;
}

/*聊天工具栏*/

.chat-bar {
  padding: 5px 15px;
  position: relative;
  margin-top: 6px;
}

.el-select{
  margin-top: 6px;
}

.chat-bar i {
  font-size: 20px;
  cursor: pointer;
  color: #495057;
}

.chat-emotion {
  position: absolute;
  z-index: 99;
  left: 35px;
  top: 10px;
  width: 390px;
  height: 140px;
  padding: 5px;
  background: #fff;
  border: 1px solid #999999;
}

.chat-bar .emot-list li {
  float: left;
}

.chat-bar .emot-list li img {
  cursor: pointer;
  border: 1px #fff solid;
}

.chat-bar .emot-list li img:hover {
  border: 1px #0066cc solid;
}

.chat-tip {
  position: absolute;
  right: 10px;
  bottom: 5px;
  font-size: 10px;
  color: #495057;
}
</style>
<style>
.item_btn .el-form-item__content{
  margin-left: 0px !important;
}
</style>